package com.ruoyi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.CreditApply;
import com.ruoyi.bizsys.domain.LoanOrder;
import com.ruoyi.bizsys.service.ICreditApplyService;
import com.ruoyi.bizsys.service.ILoanOrderService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.service.impl.BaseService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.sms.service.ISmsService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Slf4j
@Component
public class AppUserInfoService extends BaseService {

    @Autowired
    private ISmsService smsService;

    @Autowired
    ICreditApplyService creditApplyService;

    @Autowired
    ILoanOrderService loanOrderService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 获取删除理由列表
     *
     * @return
     */
    public List<SysDictData> getReason() {
        List<SysDictData> reason_cancellation = DictUtils.getDictCache("reason_cancellation");
        if (CollectionUtils.isEmpty(reason_cancellation)) {
            reason_cancellation = sysDictDataMapper.selectReason();
        }
        return reason_cancellation;
    }

    public void checkInTransitOrders(String custNo) {

        // 检查授信订单
        checkCreditInTransitOrder(custNo);

        // 检查提现订单
        checkLoanInTransitOrder(custNo);
    }

    private void checkLoanInTransitOrder(String custNo) {
        int count = loanOrderService.count(new QueryWrapper<LoanOrder>().eq("cust_no", custNo)
                .in("loan_status",
                        LoanOrder.LOAN_STATUS_9_APPROVALING,
                        LoanOrder.LOAN_STATUS_1_APPROVE_PASSED,
                        LoanOrder.LOAN_STATUS_2_INSUFFICIENT_ACCOUNT_BALANCE,
                        LoanOrder.LOAN_STATUS_3_LOAN_PENDING,
                        LoanOrder.LOAN_STATUS_6_RE_INITIATE_PAY,
                        LoanOrder.LOAN_STATUS_7_CONTRAC_GENERATED)
                .eq("state", BizConstants.BIZ_STATUS_1));
        if (count > 0) {
            throw new BusinessException(RspEnmu.LOAN_APPLY_IN_TRANSIT);
        }
    }

    private void checkCreditInTransitOrder(String custNo) {
        int count = creditApplyService.count(new QueryWrapper<CreditApply>().eq("cust_no", custNo).eq("apply_status", BizConstants.APPLY_STATUS_9_APPROVALING).eq("state", BizConstants.BIZ_STATUS_1));
        if (count > 0) {
            throw new BusinessException(RspEnmu.CREDIT_APPLY_IN_TRANSIT);
        }
    }
}